// utils/echartsAutoTooltip.ts
import { EChartsType } from 'echarts';

interface AutoTooltipOptions {
  interval?: number; // 轮播间隔(毫秒)，默认2000
  seriesIndex?: number; // 指定系列索引，默认0
  loopAllSeries?: boolean; // 是否轮播所有系列，默认false
}

export function useAutoTooltip(chart: EChartsType, options: AutoTooltipOptions = {}) {
  const { interval = 2000, seriesIndex = 0 } = options;

  let currentIndex = 0;
  let timer: number | undefined;

  // 获取数据长度
  const getDataLength = () => {
    const seriesData = chart.getOption().series as any[];
    if (!seriesData || seriesData.length === 0) return 0;
    return seriesData[seriesIndex]?.data?.length || 0;
  };

  const dataLength = getDataLength();
  if (dataLength === 0) return { start: () => {}, stop: () => {} };

  // 轮播函数
  const switchTooltip = () => {
    chart.dispatchAction({
      type: 'downplay',
      seriesIndex: seriesIndex
    });

    chart.dispatchAction({
      type: 'highlight',
      seriesIndex: seriesIndex,
      dataIndex: currentIndex
    });

    chart.dispatchAction({
      type: 'showTip',
      seriesIndex: seriesIndex,
      dataIndex: currentIndex
    });

    currentIndex = (currentIndex + 1) % dataLength;
  };

  // 开始轮播
  const start = () => {
    stop();
    timer = window.setInterval(switchTooltip, interval);

    // 鼠标事件处理
    chart.getZr().on('mousemove', stop);
    chart.getZr().on('mouseout', start);
  };

  // 停止轮播
  const stop = () => {
    if (timer) {
      clearInterval(timer);
      timer = undefined;
    }
  };

  return { start, stop };
}
